import { Injectable, UnauthorizedException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CustomerServiceAgent } from './entities/agent.entity';
import * as bcrypt from 'bcryptjs';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class CustomerServiceAuthService {
  constructor(
    @InjectRepository(CustomerServiceAgent)
    private readonly agentRepo: Repository<CustomerServiceAgent>,
    private readonly jwtService: JwtService,
  ) {}

  async register(username: string, password: string, name: string, groupId?: number, role: 'agent' | 'supervisor' = 'agent') {
    const exist = await this.agentRepo.findOne({ where: { username } });
    if (exist) throw new BadRequestException('用户名已存在');
    const hash = await bcrypt.hash(password, 10);
    const agent = this.agentRepo.create({ username, password: hash, name, role });
    return this.agentRepo.save(agent);
  }

  async validate(username: string, password: string) {
    const agent = await this.agentRepo.findOne({ where: { username } });
    if (!agent) throw new UnauthorizedException('账号不存在');
    if (!(await bcrypt.compare(password, agent.password))) throw new UnauthorizedException('密码错误');
    return agent;
  }

  async login(username: string, password: string) {
    const agent = await this.validate(username, password);
    const payload = { sub: agent.id, username: agent.username, role: agent.role };
    return {
      access_token: this.jwtService.sign(payload),
      agent: {
        id: agent.id,
        username: agent.username,
        name: agent.name,
        role: agent.role,
      },
    };
  }

  async getProfile(agentId: number) {
    return this.agentRepo.findOne({ where: { id: agentId } });
  }
} 